package gui;


import controler.SudokuControler;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.EventListener;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import rules.Rule;
import utils.SudokuMatrixIO;



/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * SudokuBoardGUI.java
 *
 * Created on 20.04.2010, 20:41:46
 */

/**
 *
 * @author creatro
 */
public class SudokuBoardGUI extends JFrame {

    private JPanel jContantPane = null;
    private JFrame jFrame = null;
    private int rcbCount = 0;
    private JPanel panelBoard = null;
    private JPanel panelButtons = null;
    private JPanel panelRule = null;
    private JPanel panelChoose = null;
    static private final String newline = "\n";
    private JButton upButton=null;
    private JButton downButton=null;
    //private JButton fileOpenButton=null;
    private OpenButton fileOpenButton=null;

    private String separator = System.getProperty( "file.separator" );

    private JFileChooser fc = new JFileChooser();

    /** Creates new form SudokuBoardGUI */
    public SudokuBoardGUI() {

        super("Sudoku");
        initComponents();
       
    }
     /** Creates new form SudokuBoardGUI */
    public SudokuBoardGUI(int num) {

        super("Sudoku");
        initComponents();
        rcbCount = num;

    }
    public JPanel getJContantPane(){

        if (jContantPane == null){
            jContantPane = new JPanel();
            jContantPane.setLayout(new BorderLayout());
            
        }
        return jContantPane;
    }
    public JPanel getJButtonsPane(){
        if (panelButtons == null){
            panelButtons = new JPanel();
            panelButtons.setLayout(new FlowLayout(FlowLayout.LEFT, 1, 1));

        }
        return panelButtons;
    }
     public JPanel getJRulePane(){
        if (panelRule == null){
            panelRule = new JPanel();
            //panelRule.setSize(40, 20);
            GridLayout gLayout = new GridLayout(7, 1, 4, 5);
            panelRule.setLayout(gLayout);

        }
        return panelRule;
    }
    public JPanel getJChoosePane(){
        if (panelChoose == null){
            panelChoose = new JPanel();
            panelChoose.setLayout(new BorderLayout());
            Dimension dim = panelChoose.getPreferredSize();
            dim.width = 100;
            panelChoose.setPreferredSize(dim);

        }
        return panelChoose;
    }
    public JFrame getJFrame(){
        if (jFrame == null){
            jFrame = new JFrame("Sudoku");
            jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
           // jFrame.setSize(d.height, d.height);
           // jFrame.setLocation((d.width - getSize().width), (d.height - getSize().height));
            
            jFrame.setSize((int)(d.height / 1.2),(int) (d.height / 1.2));
            //jFrame.setLocation((int)((d.width - getSize().width) / 1.2), (int)((d.height - getSize().height) / 1.2));
            jFrame.setLocationByPlatform(true);
            jFrame.setContentPane(this.getJContantPane());
            jFrame.setResizable(true);
            jFrame.setLayout(new BorderLayout());
            createBaord();
            getOpenButton();
            //createButtons();
            createChoose();
            
        }
        return jFrame;
    }
    public void createBaord( ){

        JPanel tempPanel = new JPanel();
        tempPanel.setLayout(new BorderLayout());
        panelBoard = new JPanel();
        panelBoard.setBackground(Color.black);
        panelBoard.setName("panelBoard");
        int blNum = (int)Math.sqrt(rcbCount);
        panelBoard.setLayout( new GridLayout(blNum, blNum, 4, 4));
        tempPanel.add(panelBoard, BorderLayout.CENTER);

        tempPanel.add(getJButtonsPane(),BorderLayout.NORTH);
        getJContantPane().add(tempPanel);

        // initiliaze new fount
        Font font = new Font(Font.SANS_SERIF,Font.BOLD,32);
        JTextField textField = null;

        JPanel panel = null;

        for (int block=0; block<rcbCount; block++){
           
           panel= new JPanel(new GridLayout(blNum,blNum));

           for (int field=0; field<rcbCount; field++){

               textField = new JTextField();
               textField.setFont(font);
               textField.setName(block+";"+field);
               textField.setEditable(false);
               textField.setHorizontalAlignment(JTextField.CENTER);
               panel.add(textField);
           }
           panelBoard.add(panel,BorderLayout.PAGE_START );
           
         }
     }
    public void setRowColBlockCount(int num){

        rcbCount = num;
    }
    public void setFild(int block, int field, int value, Color color){
        JPanel panelBlock = (JPanel)panelBoard.getComponent(block);
        JTextField txtField = (JTextField)panelBlock.getComponent(field);
        txtField.setText(""+value);
        txtField.setBackground(color);
    }
    public void setFild(int block, int field, Color color){
        JPanel panelBlock = (JPanel)panelBoard.getComponent(block);
        JTextField txtField = (JTextField)panelBlock.getComponent(field);
        txtField.setBackground(color);
    }
    public JTextField setMouseListener(int block, int field, MouseListener ml){
        JPanel panelBlock = (JPanel)panelBoard.getComponent(block);
        panelBlock.addMouseListener(ml);
        //panelBoard.addMouseListener(ml);
        JTextField txtField = (JTextField)panelBlock.getComponent(field);
        txtField.addMouseListener(ml);
        return txtField;
    }
    public JButton createButton(String name){
        
        MyButton button = new MyButton("");
        button.setSize(40, 40);
        button.setActionCommand(name);
       // button.setToolTipText(name);
        return button;
        
    }
     public JButton createButton(Icon icon, String comandName){

        MyButton button = new MyButton(icon);
        button.setSize(40, 40);
        button.setMargin(new Insets(0,0,0,0));
        button.setActionCommand(comandName);
        return button;

    }
    public JTextField getField(int block, int field){
        JPanel panelBlock = (JPanel)panelBoard.getComponent(block);
        JTextField txtField = (JTextField)panelBlock.getComponent(field);
        return txtField;
    }
    public JButton getOpenButton(){
        if (fileOpenButton==null){
            //getJContantPane().add( getJButtonsPane(),BorderLayout.NORTH);
            String iconName = "/images/Open16.gif";
            URL url = SudokuControler.class.getResource(iconName);
            Icon icon = null;
           if (url == null){
             icon = new ImageIcon("."+iconName);
           } else{
             icon = new ImageIcon(url);

           }
            fileOpenButton = new OpenButton(icon);
            fileOpenButton.setActionCommand("Load a File");
            getJButtonsPane().setBackground(new Color(221,221,221));
            getJButtonsPane().add(fileOpenButton);
        }
        return fileOpenButton;
     }
    public void createChoose(){
        getJContantPane().add( getJChoosePane(),BorderLayout.EAST);
        upBotton().setVisible(false);
        downBotton().setVisible(false);
        getJChoosePane().add( getJRulePane(), BorderLayout.CENTER);
        
    }
    public JButton upBotton(){
        if (upButton == null){
           String iconName = "/images/Up.gif";
            URL url = SudokuControler.class.getResource(iconName);
            Icon icon = null;
           if (url == null){
             icon = new ImageIcon("."+iconName);
           } else{
             icon = new ImageIcon(url);

           }
          //Icon icon = new ImageIcon("images/Up.gif");
          upButton = new JButton(icon);
          upButton.setActionCommand("up");
          getJChoosePane().add(upButton, BorderLayout.NORTH);
        }
       return upButton;

    }
    public JButton downBotton(){
        if (downButton == null){
           //Icon icon = new ImageIcon("images/Down.gif");
            String iconName = "/images/Down.gif";
            URL url = SudokuControler.class.getResource(iconName);
            Icon icon = null;
           if (url == null){
             icon = new ImageIcon("."+iconName);
           } else{
             icon = new ImageIcon(url);

           }
           downButton = new JButton(icon);
           downButton.setActionCommand("down");
           getJChoosePane().add(downButton, BorderLayout.SOUTH);
        }
       return downButton;

    }

    public Component[] getButtons(){
        return getJButtonsPane().getComponents();
    }
    public void reset(){
         JPanel panelBlock = null;
        for (int i=0; i<panelBoard.getComponentCount(); i++){
            panelBlock = (JPanel)panelBoard.getComponent(i);
            for (int j=0; j<panelBlock.getComponentCount(); j++){
                 JTextField txtField = (JTextField)panelBlock.getComponent(j);
                 txtField.setText("");
            }
        }
    }
    public String getSelectedFile(){

        
        int returnVal = fc.showOpenDialog(getJButtonsPane());
        File file = null;
        String filename = null;
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            file = fc.getSelectedFile();
            filename = file.getPath();
            //This is where a real application would open the file.
        } else {
            filename = "";
        }
       return filename;
    }
    public String getSavePhat(String fn){

        File file = new File(fn);
        fc.setCurrentDirectory(file);
        int returnVal = fc.showSaveDialog(getJButtonsPane());
          
        String filename = null;
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            file = fc.getSelectedFile();
            filename = file.getPath();
            //This is where a real application would open the file.
        } else {
            filename = "";
        }
       return filename;
    }
    public int getSaveDialog(){
          int option = JOptionPane.showConfirmDialog(
                        getJFrame(),
                        "To you want to Save this game?",
                        "Save Sudoku",
                        JOptionPane.YES_NO_OPTION,
                        JOptionPane.QUESTION_MESSAGE );
          return option;
    }
   public void showRules( EventListener el, Collection cl, int min, int max )
   {
      System.out.println("showRules");
      getJRulePane().removeAll();
      Icon icon = null;
      Iterator itr = cl.iterator();
      String iconName = null;
       while (itr.hasNext()){
        Rule rl = (Rule)itr.next();
/*
          iconName = "/images/"+rl.getName()+".gif";
          URL url = SudokuControler.class.getResource(iconName);
           if (url == null){
             icon = new ImageIcon("."+iconName);
           } else{
             icon = new ImageIcon(url);

           }
        */

        //JButton button = createButton(icon,rl.getName());
        JButton button = createButton(rl.getName());

       // JButton button = createButton("");

        button.setBackground(SudokuControler.getWeightColor(rl.getWeight(rl.getQuadrat()), min, max));
        button.addActionListener((ActionListener) el);
        button.addMouseListener((MouseListener) el);
        getJRulePane().add(button);
       }
      getJRulePane().updateUI();

   }
   public void clearRulesList(){
        getJRulePane().removeAll();
        getJRulePane().updateUI();
   }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
    * @param args the command line arguments
    */
//    public static void main(String args[]) {
//        java.awt.EventQueue.invokeLater(new Runnable() {
//            public void run() {
//              SudokuBoardGUI sudokuBoard = new SudokuBoardGUI(9);
//              sudokuBoard.getJFrame().setVisible(true);
//
//            }
//        });
//    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    // End of variables declaration//GEN-END:variables

}
